package center

import (
	//"encoding/json"
	"fmt"
	"log"
	"math/rand"
)

//是否新用户
func p0001(p *Packet, coni *Conninfo) {
	user_code := bytesTostring(p.data[0:20])
	p.data = make([]byte, 0)
	var user_id int32 = -1
	var user_info *User_info
	rwlock_uinfo.RLock()
	for key, val := range user_info_map {
		if val.user_code == user_code {
			user_id = val.user_id
			user_info = user_info_map[key]
			break
		}
	}
	rwlock_uinfo.RUnlock()
	fmt.Println("p0001 user_id:", user_id)

	if user_id >= 0 {
		//建立user_id 到socket的对应关系
		if idtosocket[user_id] != nil { //踢掉同一用户原来的链接
			user_out_line(idtosocket[user_id])
			delete(sockettoid, idtosocket[user_id])
			idtosocket[user_id].Close()
		}
		idtosocket[user_id] = coni
		sockettoid[coni] = user_id
		//===========================
		if user_info.user_name == "" {
			user_id = -1
		}
		//===========================
		p.data = append(p.data, int32ToByte(user_id)...)
		p.data_len = 4
	} else {
		result, err := dbcenter.Change("insert into user_info set user_code=?", user_code)
		if err != nil || result == nil {
			log.Print("p001 insert user_code error!", user_code)
			return
		}
		user_info = new(User_info)
		user_info.user_code = user_code
		user_info.genlist = make(map[int16]*Gen_info)
		user_info.baglist = make(map[int32]*Bag_thing)
		uid, err := result.LastInsertId()
		user_id = int32(uid)
		//建立user_id 到socket的对应关系
		idtosocket[user_id] = coni
		sockettoid[coni] = user_id
		//===========================
		user_info.user_id = user_id
		user_info.scene_id = 1
		rwlock_uinfo.Lock()
		user_info_map[user_id] = user_info
		rwlock_uinfo.Unlock()
		p.data = append(p.data, int32ToByte(-1)...)
		p.data_len = 4
	}

	p.send(coni)
}
func user_out_line(coni *Conninfo) {

	p := newPacket()
	p.cmd_code = 0x0004
	p.data = make([]byte, 0)
	p.data = append(p.data, int32ToByte(10000)...)
	p.data_len = 4
	p.send(coni)
}

//新用户注册（创建角色)
func p0002(p *Packet, coni *Conninfo) {
	user_name := bytesTostring(p.data[0:20])
	country := p.data[20]
	city := p.data[21]
	headid := p.data[22]
	p.data = make([]byte, 0)
	user_id := sockettoid[coni]
	result, err := dbcenter.Change("update user_info set user_name=?,country=?,city=?,headid=? where user_id=?", user_name, country, city, headid, user_id)

	if err != nil || result == nil { //角色名重复
		log.Print("p002 insert error!")
		p.data = append(p.data, int32ToByte(-1)...)
		p.data_len = 4
		p.send(coni)
		return
	}
	rwlock_uinfo.RLock()
	user_info := user_info_map[user_id]
	rwlock_uinfo.RUnlock()

	if user_info == nil {
		log.Print("user not found!")
		return
	}
	user_info.rwlock_user.Lock()
	defer user_info.rwlock_user.Unlock()
	user_info.user_name = user_name
	user_info.country = country
	user_info.city = city
	user_info.headid = headid

	result, err = dbcenter.Change("insert into gen_info set lvone_id=?,user_id=?", 1108, user_id)

	if err != nil {
		log.Print("p002 insert error!")
		return
	}
	if result == nil {
		log.Print("p002 insert error!")
		return
	}
	gen_info := new(Gen_info)
	_id, err := result.LastInsertId()
	gen_info.gen_info_id = int32(_id)
	gen_info.lvone_id = 1008
	gen_info.user_id = user_id
	user_info.genlist[1008] = gen_info

	p.data = append(p.data, int32ToByte(user_id)...)
	p.data_len = 4
	p.send(coni)
}

//获取用户信息
func p0011(p *Packet, coni *Conninfo) {
	user_id := byteToInt32(p.data[0:4])
	//fmt.Println("uid===>", user_id)
	rwlock_uinfo.RLock()
	user_info := user_info_map[user_id]
	rwlock_uinfo.RUnlock()

	if user_info == nil {
		log.Printf("user not exisit!")
		return
	}
	user_info.rwlock_user.RLock()
	defer user_info.rwlock_user.RUnlock()

	user_name := user_info.user_name
	headid := user_info.headid
	country := user_info.country
	city := user_info.city
	scene_id := user_info.scene_id
	t1 := [20]byte{}
	copy(t1[:], user_name)
	fmt.Println("<--0x0011-->", user_name, country, city, scene_id)
	p.data = make([]byte, 0)
	p.data = append(p.data, t1[:]...)
	p.data = append(p.data, []byte{headid}...)
	p.data = append(p.data, []byte{country}...)
	p.data = append(p.data, []byte{city}...)
	p.data = append(p.data, []byte{scene_id}...)
	p.data_len = 24
	p.send(coni)
}

//获取武将信息
func p0013(p *Packet, coni *Conninfo) {
	user_id := byteToInt32(p.data[0:4])
	rwlock_uinfo.RLock()
	user_info := user_info_map[user_id]
	rwlock_uinfo.RUnlock()

	if user_info == nil {
		fmt.Println("user not found!")
		return
	}
	user_info.rwlock_user.RLock()
	defer user_info.rwlock_user.RUnlock()
	p.data = make([]byte, 0)
	var count int32
	for _, val := range user_info.genlist {
		p.data = append(p.data, int32ToByte(val.gen_info_id)...)
		p.data = append(p.data, int16ToByte(val.lvone_id)...)
		p.data = append(p.data, int16ToByte(val.genlv)...)
		p.data = append(p.data, int32ToByte(val.attackval)...)
		p.data = append(p.data, int32ToByte(val.defensenval)...)
		count += 16
	}
	p.data_len = count
	p.send(coni)
}

//获取背包物品
func p0014(p *Packet, coni *Conninfo) {
	user_id := byteToInt32(p.data[0:4])
	rwlock_uinfo.RLock()
	user_info := user_info_map[user_id]
	if user_info == nil {
		fmt.Println("user not found!")
		rwlock_uinfo.RUnlock()
		return
	}
	rwlock_uinfo.RUnlock()
	p.data = make([]byte, 0)
	var count int32
	user_info.rwlock_user.RLock()
	defer user_info.rwlock_user.RUnlock()

	for _, val := range user_info.baglist {
		p.data = append(p.data, int32ToByte(val.prop_id)...)
		p.data = append(p.data, []byte{val.prop_lv}...)
		p.data = append(p.data, int32ToByte(val.prop_num)...)
		count += 9
	}
	p.data_len = count
	p.send(coni)
}

//获取世界地图信息
func p0015(p *Packet, coni *Conninfo) {
	user_id := byteToInt32(p.data[0:4])
	rwlock_uinfo.RLock()
	user_info := user_info_map[user_id]
	rwlock_uinfo.RUnlock()
	if user_info == nil {
		fmt.Println("user not found!")
		return
	}
	rwlock_country.RLock()
	defer rwlock_country.RUnlock()
	p.data = make([]byte, 0)
	var count int32
	for _, val := range country_map {
		for _, _val := range val.city_list {
			p.data = append(p.data, []byte{_val.city_id}...)
			p.data = append(p.data, []byte{_val.country}...)
			p.data = append(p.data, int32ToByte(val.user_id)...)
			count += 6
		}
	}
	p.data_len = count
	p.send(coni)
}

//获取区域玩家信息
func p0016(p *Packet, coni *Conninfo) {
	user_id := byteToInt32(p.data[0:4])
	city := p.data[4]
	rwlock_uinfo.RLock()
	user_info := user_info_map[user_id]
	defer rwlock_uinfo.RUnlock()

	if user_info == nil {
		fmt.Println("user not found!")
		return
	}

	p.data = make([]byte, 0)
	var count int32
	for _, val := range user_info_map {
		if city == val.city {
			p.data = append(p.data, int32ToByte(val.user_id)...)
			t1 := [20]byte{}
			copy(t1[:], val.user_name)
			p.data = append(p.data, t1[:]...)
			count += 24
		}
	}
	p.data_len = count
	p.send(coni)
}

//玩家进入场景,返回当前场景的所有玩家的信息
func p0031(p *Packet, coni *Conninfo) {
	user_id := byteToInt32(p.data[0:4])
	scene_id := p.data[4]
	rwlock_uinfo.RLock()
	user_info := user_info_map[user_id]
	rwlock_uinfo.RUnlock()
	if user_info == nil {
		fmt.Println("user not found!", user_id)
		return
	}
	if scene_id > 30 {
		fmt.Println("scene_id too big", scene_id)
	}
	//取得之前的场景
	scene_List_lock.RLock()
	pre_scene := scene_List[user_info.scene_id]
	scene_List_lock.RUnlock()
	if pre_scene == nil {
		fmt.Println("pre_scene not found!", scene_id)
	}
	result, err := dbcenter.Change("update user_info set scene_id=? where user_id=?", scene_id, user_id)

	if err != nil {
		log.Print("p0031 insert error!")
		return
	}
	if result == nil {
		log.Print("p0031 insert error!")
		return
	}
	scene_List_lock.RLock()
	scene_info := scene_List[scene_id]
	scene_List_lock.RUnlock()
	if scene_info == nil {
		fmt.Println("scene not found!", scene_id)
		return
	}
	scene_info.rwlock_scene.Lock()
	user_info.rwlock_user.Lock()
	scene_info.user_list[user_id] = user_info
	user_info.scene_id = scene_id
	user_info.rwlock_user.Unlock()
	scene_info.rwlock_scene.Unlock()

	p.data = make([]byte, 0)

	scene_info.rwlock_scene.RLock()
	var dataLen int32
	for _, val := range scene_info.user_list {
		user_info = val
		user_info.rwlock_user.RLock()
		if user_id == user_info.user_id && user_info.pos.x == 0 {
			user_info.pos.x = int32(rand.Intn(1000))
			user_info.pos.y = int32(rand.Intn(100)) + 400
			fmt.Println("user position", user_info.pos.x, user_info.pos.y)
		}
		t1 := [20]byte{}
		copy(t1[:], user_info.user_name)
		p.data = append(p.data, int32ToByte(user_info.user_id)...)
		p.data = append(p.data, t1[:]...)
		p.data = append(p.data, []byte{user_info.headid}...)
		p.data = append(p.data, int32ToByte(user_info.pos.x)...)
		p.data = append(p.data, int32ToByte(user_info.pos.y)...)
		dataLen += 33
		user_info.rwlock_user.RUnlock()
	}
	p.data_len = dataLen
	scene_info.rwlock_scene.RUnlock()
	p.send(coni)
	user_change_scene(user_info, pre_scene, scene_info) //广播给前场景0x0043包，和当前场景0x0041包
}
